# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/7/24

library(ggrepel)
library(ropls)
library(pROC)
library(egg)
library(randomForest)
library(Boruta)
library(magrittr)
library(optparse)
library(gbm)
library(caret)
library(tidyverse)

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

option_list <- list(
  make_option("--i", default = "./AllMet_Raw.txt", type = "character", help = "metabolite data file"),
  make_option("--g", default = "./group.txt", type = "character", help = "sample group file"),
  make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file")
)
opt <- parse_args(OptionParser(option_list = option_list))

options(digits = 3)


sampleInfo <- read_tsv(opt$g) %>%
  rename(SampleID = Sample) %>%
  select(c("SampleID", "ClassNote"))

head(sampleInfo)

parent <- paste0("./")
createWhenNoExist(parent)

originalData <- read_tsv(opt$i) %>%
  gather("SampleID", "Value", -Metabolite) %>%
  spread(Metabolite, "Value")

originalColumnNames<-colnames(originalData)

data <- originalData %>%
  inner_join(sampleInfo, by = c("SampleID")) %>%
  mutate(ClassNote = factor(ClassNote, levels = unique(ClassNote)))
allTrainData <- data %>%
  column_to_rownames("SampleID")

load("../../folds.RData")
predictLists <- (1:k) %>%
  map(function(k) {
    testData <- allTrainData[flds[[k]],]
    trainData <- allTrainData[-flds[[k]],]
    minobsinnode <- ceiling(((nrow(trainData) * 0.5 - 1) / 2) - 1)
    gbRs <- gbm(ClassNote ~ ., data = trainData, distribution = "multinomial", n.trees = 400, interaction.depth = 1,
                shrinkage = 0.03, n.minobsinnode = minobsinnode, bag.fraction = 0.5)
    testDataNoClass <- testData %>%
      select(-c("ClassNote"))
    predBST <- predict(gbRs, newdata = testDataNoClass, n.trees = 400, type = "response")
    p.predBST <- apply(predBST, 1, which.max)
    predictRs <- colnames(predBST)[p.predBST]
    rownames(predBST) <- rownames(testData)
    predDf <- predBST %>%
      as.data.frame(check.names = F, stringsAsFactors = F) %>%
      rownames_to_column("SampleID") %>%
      set_colnames(c("SampleID", colnames(predBST))) %>%
      rowwise() %>%
      do({
        result <- as.data.frame(.)
        values <- result[1,] %>%
          select(-c("SampleID")) %>%
          unlist()
        result$Probability <- max(values)
        result
      }) %>%
      select(c("SampleID", "Probability")) %>%
      add_column(Prediction = predictRs)
    predictFinalDf <- sampleInfo %>%
      filter(SampleID %in% rownames(testData)) %>%
      left_join(predDf, by = c("SampleID")) %>%
      rename(Sample = SampleID) %>%
      select(-c("Probability"), "Probability") %>%
      mutate(Test_in_CV_fold = k)

    predDf1 <- predBST %>%
      as.data.frame(check.names = F, stringsAsFactors = F) %>%
      rownames_to_column("SampleID") %>%
      set_colnames(c("SampleID", colnames(predBST))) %>%
      rowwise() %>%
      do({
        result <- as.data.frame(.)
        values <- result[1,] %>%
          select(-c("SampleID")) %>%
          unlist()
        result$Value <- values[1]
        result
      }) %>%
      select(c("SampleID", "Value")) %>%
      add_column(Prediction = predictRs)
    predictFinalDf1 <- sampleInfo %>%
      filter(SampleID %in% rownames(testData)) %>%
      left_join(predDf1, by = c("SampleID")) %>%
      mutate(Fold = k)

    list(predictDf = predictFinalDf, plotData = predictFinalDf1)
  })
predictDf <- predictLists %>%
  map_dfr(function(list) {
    list$predictDf
  })
predictDf
write.csv(predictDf, "GB_Prediction_CV.csv", row.names = F)

plotData <- predictLists %>%
  map_dfr(function(list) {
    list$plotData
  })
plotData

write_tsv(plotData, "Classification_Result.txt")

pre_summary = table(predictDf$ClassNote, predictDf$Prediction)

print(pre_summary)
summaryTb <- pre_summary %>%
  as.data.frame() %>%
  as_tibble() %>%
  spread(Var2, "Freq")
print("=log=")
print(summaryTb)
summaryMatrix <- summaryTb %>%
  select(-"Var1") %>%
  as.matrix()
diagSum <- sum(diag(summaryMatrix))
sum <- sum(summaryMatrix)
predictive <- (diagSum / sum) %>%
  round(3)
finalSummaryTb <- summaryTb %>%
  mutate(`Model predictive accuracy` = c(predictive, "")) %>%
  rename(` ` = Var1)
print(finalSummaryTb)

write_csv(finalSummaryTb, "GB_Prediction_Summary_CV_Overall.csv")











